package com.his.config;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;

import java.util.Date;

/**
 * token工具
 */
public class JwtUtils {
    private JwtUtils() {
    }

    private static final String USERNAME_FIELD = "username";

    private static final String SECRET = "askhdklajsdkl";


    /**
     * 创建token
     *
     * @param username
     * @return
     */
    public static String createJwt(String username) {
        Date now = new Date();
        Date date = new Date(now.getTime() + 30 * 60 * 1000);//当前时间加30分钟
        JWTCreator.Builder builder = JWT.create();
        Algorithm algorithm = Algorithm.HMAC256(SECRET);
        return builder.withClaim(USERNAME_FIELD, username)
                .withExpiresAt(date)
                .sign(algorithm);

    }


    /**
     * 验证token
     *
     * @param jwt
     * @return
     */
    public static boolean verify(String jwt) {
        Algorithm algorithm = Algorithm.HMAC256(SECRET);
        try {
            JWT.require(algorithm)
                    .build()
                    .verify(jwt);
            return true;
        } catch (JWTVerificationException e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 获取token信息
     *
     * @param jwt
     * @return
     */
    public static String getUsername(String jwt) {
        Algorithm algorithm = Algorithm.HMAC256(SECRET);
        return JWT.require(algorithm)
                .build()
                .verify(jwt)
                .getClaim(USERNAME_FIELD)
                .asString();
    }
}
